package com.oms.web.contronller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.oms.domain.User;
import com.oms.runningdata.SystemInitData;
import com.oms.service.AcknowledgementService;
import com.oms.service.MessageService;
import com.oms.service.UserService;
import com.oms.util.MD5Util;
import com.oms.util.VerifyUtil;
import com.oms.web.form.ChangePasswordForm;
import com.oms.web.form.LoginForm;
import com.oms.web.form.RegisteForm;
import com.oms.web.form.ResetPasswordForm;

@Controller
public class UserController {
	
	@Resource
	private UserService userService;
	
	@Resource
	private MessageService messageService;
	
	@Resource
	private AcknowledgementService acknowledgementService;
	
	
	//获取注册页面，并初始化
	@RequestMapping(value="/registerPage",method=RequestMethod.GET)
	public String registerPage(Map<String,Object> map){
		map.put("registeForm", new RegisteForm());	//向request域放入注册用到的表单对象
		return "user/register";
	}
	
	//注册业务
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String register(@Valid RegisteForm registeForm ,Errors result,HttpServletRequest request,HttpServletResponse response){
		Boolean validState=true;
		if(result.getErrorCount()>0){	//JSR303校验结果，不通过的条数是否大于0
			System.out.println("基本验证出错！");
			return "user/register";
		}
		if(!registeForm.getPassword().equals(registeForm.getPassword2())){	//对比两次填写的密码是否相同
			System.out.println("两次输入密码不一致"+"password1="+registeForm.getPassword()+",password2="+registeForm.getPassword2());
			request.setAttribute("passwordMsg", "两次输入的密码不一致！");
			validState=false;
		}
		if(!request.getSession().getAttribute("valistr").equals(registeForm.getValistr())){	//校验验证码
			System.out.println("验证码不正确,正确的验证码为:"+registeForm.getValistr());
			request.setAttribute("valistrMsg", "验证码错误！");
			validState=false;
//			return "register";
		}
		if(!validState){
			validState=true;
			return "user/register";
		}
		else{
			System.out.println("开始注册账号");
			request.getSession().setAttribute("valistr", UUID.randomUUID().toString());
			Boolean registeResult=null;
			try{
				registeResult=userService.registeUser(registeForm);
			}catch(RuntimeException e){
				System.out.println("注册过程抛出异常");
				request.setAttribute("failTitle", "注册失败!");
				request.setAttribute("failContent", "失败原因是:"+e.toString());
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/registerPage.do");
				return "fail";
			}
			if(registeResult==true){
				request.setAttribute("succeedTitle", "注册成功！请前往注册邮箱激活账号");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "success";
			}else{
				request.setAttribute("failTitle", "注册失败!");
				request.setAttribute("failContent", "失败原因是...");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/registerPage.do");
				return "fail";
			}			
		} 
	}
	
	//激活邮箱注册的用户
	@RequestMapping(value="/userActive",params={"activeCode"},method=RequestMethod.GET)
	public String activeUser(HttpServletRequest request,HttpServletResponse response,String activeCode){
//		System.out.println(activeCode);
		if(activeCode==null){	//激活码为空
			request.setAttribute("failTitle", "激活失败!");
			request.setAttribute("failContent", "失败原因是:"+"激活码不能为空"+"。10秒后回到主页");
			response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
			return "fail";
		}
		try{
			User user=userService.activeUser(activeCode);
			user.setActiveState(true);
			request.getSession().setAttribute("user", user);
		}catch(RuntimeException e){
			request.setAttribute("failTitle", "激活失败!");
			request.setAttribute("failContent", "失败原因是:"+e.toString()+"。10秒后跳转到主页");
			response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
			return "fail";
		}
		request.setAttribute("succeedTitle", "激活成功！即将自动登陆账号！");
		response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
		return "success";
	}
	
	//获取登录页面
	@RequestMapping(value="/loginPage")
	public String getLoginPage(HttpServletRequest request){
		request.getSession().setAttribute("forwardPage", request.getHeader("Referer"));	//获取发送请求的Url，并将Url存入session域中
		request.setAttribute("loginForm", new LoginForm());
		return "user/login";
	}
	
	//邮箱登录业务
	@RequestMapping(value="/loginByEmail",method=RequestMethod.POST)
	public String loginByEmail(HttpServletRequest request,HttpServletResponse response,@Valid LoginForm loginForm,Errors errors,Boolean autologin) 
			throws UnsupportedEncodingException{
		System.out.println("准备开始登录");
		System.out.println("email="+loginForm.getEmail()+";password="+loginForm.getPassword());
		User user=null;
		String passwordEncrypt= MD5Util.enCryptPassword(loginForm.getPassword());
		try{
			user=userService.loginByEmail(loginForm.getEmail(), passwordEncrypt);
			request.getSession().setAttribute("user", user);
		}catch(RuntimeException e){
			request.setAttribute("errorMsg", e.getMessage()); 
			return "user/login";
		}
		if(user==null){
			request.setAttribute("errorMsg", "账号密码不正确");
			return "user/login";
		}
		if(!user.getActiveState()){
			request.setAttribute("errorMsg", "该账号尚未激活！");
		}
		if(user.getAccountState().equals(Short.valueOf("1"))){
			request.setAttribute("errorMsg", "该账号已被封直到："+user.getAccountStateDeadline());
		}
//		System.out.println(autologin);
		Integer unReadMsgNumber=acknowledgementService.getUnReadMsgCount(user);
		System.out.println(unReadMsgNumber);
		request.getSession().setAttribute("unReadMsgNumber",unReadMsgNumber);
		if(autologin!=null)	//自动勾选了自动登录
		{
			Cookie autoLoginC = new Cookie("autoLogin",URLEncoder.encode(user.getEmail()+":"+passwordEncrypt,"utf-8"));
			autoLoginC.setPath("/");
			autoLoginC.setMaxAge(3600*24*30);
			response.addCookie(autoLoginC);
		}
			return "redirect:"+request.getSession().getAttribute("forwardPage");
	}
	
	//注销登录
	@RequestMapping(value="/loginOut")
	public String loginOut(HttpServletRequest request,HttpServletResponse response){
		if(request.getSession(false)!=null){	//判断session是否存在
			request.getSession().invalidate();	//杀死session
			Cookie autoLoginC=new Cookie("autoLogin","");	//覆盖原自动登录的Cookie
			autoLoginC.setPath("/");
			autoLoginC.setMaxAge(0);
			response.addCookie(autoLoginC);
		}
		return "redirect:" +request.getHeader("Referer");
	}
	
	//查看个人信息
	//rest方式查看一条信息的详情
	@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
	public String userMsgInput(@PathVariable("id") Integer id,HttpServletRequest request,HttpServletResponse response){
		User user=(User) request.getSession().getAttribute("user");
		if( user!=null && user.getUserId()==id ){	//如果要查看信息的是当前用户的信息，直接从session域中取出该用户的信息用于显示
			System.out.println("从session域中取用户的信息");
			request.setAttribute("userMsg", user);
			request.setAttribute("editAble", true);
		}else{
			System.out.println("从数据库中取用户的信息");
			user=userService.findUserById(id);	//从数据库中取出要显示的用户信息
			if(user==null){
				request.setAttribute("failTitle", "访问位置有误!");
				request.setAttribute("failContent", "该用户不存在!");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}
			request.setAttribute("userMsg", user);
		}
		request.setAttribute("genders", SystemInitData.genders);
		request.setAttribute("educations", SystemInitData.educationBackground);

/*		System.out.println("开始调用运行时数据");
		for(Entry<Integer, String> entry:SystemInitData.educationBackground.entrySet()){ 
			System.out.println(entry.getKey()+"--->"+entry.getValue()); 
		}*/

		return "user/userMsgPage";
	}  
 	

	
	
	@RequestMapping("/uploadUserHeadPortrait")
	public String uploadUserHeadPortrait(@RequestParam("file") MultipartFile file,HttpServletRequest request){
		
		System.out.println(file);
		if(file!=null){
			System.out.println("name:"+file.getName()+";size:"+file.getSize()+";type:"+file.getContentType()+";origanname:"+file.getOriginalFilename());			
		}
//		request.getSession().setAttribute("forwardPage", request.getHeader("Referer"));
		return "redirect:" +request.getHeader("Referer");
	}
	
	//修改密码业务
	@RequestMapping(value="/changePasswordPage",method=RequestMethod.GET)
	public String changePasswordPage(Map<String,Object> map){
		map.put("changePasswordForm", new ChangePasswordForm());	//向request域放入修改密码要用的密码输入表单
		return "user/changePassword";
	}
	
	//修改密码业务
	@RequestMapping(value="/changePassword",method=RequestMethod.POST)
	public ModelAndView changePassword(@Valid ChangePasswordForm changePasswordForm,Errors result,HttpServletRequest request){
		User user=(User) request.getSession().getAttribute("user");
		//对传入的密码进行加密操作
		String encryptPassword=MD5Util.enCryptPassword(changePasswordForm.getOldPassword());
		
		System.out.println("password1="+ changePasswordForm.getNewPassword1()+";password2="+changePasswordForm.getNewPassword2());
		//开始数据校验
		if(!changePasswordForm.getNewPassword1().equals(changePasswordForm.getNewPassword2())){
			ModelAndView changPassword=new ModelAndView("user/changePassword");
			changPassword.addObject("errorMsg", "两次密码不一致");
			return changPassword;
		}
		if(!user.getPassword().equals(encryptPassword)){
			ModelAndView changPassword=new ModelAndView("user/changePassword");
			changPassword.addObject("errorMsg", "原密码不正确");
			return changPassword;
		}
		//开始修改密码
		user.setPassword(MD5Util.enCryptPassword(changePasswordForm.getNewPassword1()));
		userService.update(user);
		
		ModelAndView userInfo=new ModelAndView("user/userMsgPage");
		userInfo.addObject("userMsg", user);
		return userInfo;
	}
	
	//通过邮箱找回密码
	@RequestMapping(value="/forgotPasswordByEmail",method=RequestMethod.POST)
	public String forgotPasswordByEmail(String email,String valistr,HttpServletRequest request,
			HttpServletResponse response){
		
		//校验邮箱格式
		if(email==null || !VerifyUtil.checkEmail(email)){	
			request.setAttribute("emailMsg", "邮箱格式错误");
			return "user/forgotPasswordByEmali";
		}
		//校验验证码
		if(valistr==null || !request.getSession().getAttribute("valistr").equals(valistr)){	//校验验证码
			System.out.println("验证码不正确,正确的验证码为:"+request.getSession().getAttribute("valistr"));
			request.setAttribute("valistrMsg", "验证码错误！");
			return "user/forgotPasswordByEmali";
		}
		
		//开始事物
		try {
			userService.forgotPasswordByEmail(email);
		} catch (RuntimeException e) {
			if(e.getMessage().equals("1")){
				request.setAttribute("failTitle",e.getMessage()+";系统拒绝操作!");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}else if(e.getMessage().equals("2")){
				request.setAttribute("errorMsg",e.getMessage()+";该用户未激活！请前往激活！");
				return "user/forgotPasswordByEmali";
			}
			request.setAttribute("failTitle", "重置密码失败");
			request.setAttribute("failContent",e.getMessage());
			response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
			return "fail";
		}
		request.setAttribute("succeedTitle", "密码重置邮件已发送");
		request.setAttribute("failContent", "请在24小时内前往修改！");
		response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
		return "success";
	}
	
	/**
	 * 通过邮箱的重置码跳到重置密码的页面
	 */
	@RequestMapping(value="/resetPasswordByEmail",method=RequestMethod.GET)
	public String resetPassword(String resetCode,
			HttpServletRequest request,HttpServletResponse response){
		
		ResetPasswordForm resetPasswordForm=new ResetPasswordForm();
		try{
			User user=userService.applyResetPawByEmail(resetCode);		
			resetPasswordForm.setResetCode(user.getActiveCode());
		}catch(RuntimeException e){
			if(e.getMessage().equals("1") || e.getMessage().equals("2")){
				request.setAttribute("failTitle", "重置请求失败!");
				request.setAttribute("failContent", "失败原因是:充值码无效");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}else if(e.getMessage().equals("3")){
				request.setAttribute("failTitle", "重置请求失败!");
				request.setAttribute("failContent", "失败原因是:该注册账号未激活");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}else if(e.getMessage().equals("4")){
				request.setAttribute("failTitle", "重置请求失败!");
				request.setAttribute("failContent", "失败原因是:重置码已过期");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}else if(resetPasswordForm.getResetCode()==null){
				request.setAttribute("failTitle", "系统拒绝操作！");
				request.setAttribute("failContent", "10秒后跳转到主页");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}
			request.setAttribute("failTitle", "系统拒绝操作！");
			request.setAttribute("failContent", "10秒后跳转到主页");
			response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
			return "fail";
		}
		request.setAttribute("resetPasswordForm", resetPasswordForm);
		return "user/resetPassword";
	}
	
	
	//重置用户密码
	@RequestMapping(value="/resetPassword",method=RequestMethod.POST)
	public String resetPassword(@Valid ResetPasswordForm resetPasswordForm,Errors errors,HttpServletRequest request,
			HttpServletResponse response){

		//校验数据
		if(resetPasswordForm==null){	//激活码为空
			request.setAttribute("failTitle", "重置失败!");
			request.setAttribute("failContent", "失败原因是:"+"重置码不能为空"+"。10秒后回到主页");
			response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
			return "fail";
		}if(!resetPasswordForm.getNewPassword1().equals(resetPasswordForm.getNewPassword2())){
			request.setAttribute("errorMsg", "两次输入密码不一致");
			return "redirect:" +request.getHeader("Referer");
		}
		try{
			User user=userService.resetPassword(resetPasswordForm.getResetCode(), resetPasswordForm.getNewPassword1());			
			request.getSession().setAttribute("user", user);
		}catch(RuntimeException e){
			if(e.getMessage().equals("1") || e.getMessage().equals("2")){
				request.setAttribute("failTitle", "重置请求失败!");
				request.setAttribute("failContent", "失败原因是:充值码无效");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}else if(e.getMessage().equals("3")){
				request.setAttribute("failTitle", "重置请求失败!");
				request.setAttribute("failContent", "失败原因是:该注册账号未激活");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}else if(e.getMessage().equals("4")){
				request.setAttribute("failTitle", "重置请求失败!");
				request.setAttribute("failContent", "失败原因是:重置码已过期");
				response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
				return "fail";
			}
			request.setAttribute("failTitle", "系统拒绝操作！");
			request.setAttribute("failContent", "10秒后跳转到主页");
			response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
			return "fail";
		}
		request.setAttribute("succeedTitle", "修改密码成功！即将自动登陆账号！");
		response.setHeader("REFRESH", "10;URL=/organizationmanagement/index.jsp");
		return "success";
	}
	
	
	
	

}
